import random,time,sys,os,pygame,DeckEditor,MapEditor
from pygame.locals import *

boardSizeX = 630
boardSizeY = 630
boardSpacesX = 9
boardSpacesY = 9
bufferX = 45
bufferY = 45
screenSizeX = 1280
screenSizeY = 720
deck0 = None
deck1 = None
hand0 = None
hand1 = None
discard0 = None
discard1 = None
aiCounter = 0
aiMoveList = []
victoryCheckNow = False
selected = None
rightClick = None
screen = None
backgroundSurface = None
mobSprites = None
statSprites = None
spotSprites = None
bigCardSprites = None
menuButtons = None
damageSprites = None
smallCardSprites =None
cardSpritesSelf = None
cardSpritesOpp = None
resourceSprites = pygame.sprite.Group()
messageSprites = pygame.sprite.Group()
turn = 0
change = False
resources0 = [4,4,4,4,4]
resources1 = [4,4,4,4,4]
        
def load_image(name,colorkey):
    '''loads an image from the data folder'''
    fullname = os.path.join("data", name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print "Cannot load image:", name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)

    return image

def screenSetup():
    global backgroundSurface
    pygame.init()
    pygame.display.set_mode((1280,720))
    pygame.display.set_caption('Frontier (title pending)')
    screen = pygame.display.get_surface()
    backgroundFileName = os.path.join("data","menuBackground.png") 
    backgroundSurface = pygame.image.load(backgroundFileName) 
    screen.blit(backgroundSurface,(0,0))
    pygame.display.flip()
    return screen

def boardSetup(fileName):
    #initialize the globals
    global spotSprites
    
    #open the file
    filepath = os.path.join("maps",fileName)
    f = open(filepath,"r")
    
    #create a holder for the file data
    board = []
    
    #read the file and fill board
    for line in f:
        if line != "end":
            board.append(line)
    
    #determine the size of each rect
    spaceX = boardSizeX/boardSpacesX
    spaceY = boardSizeY/boardSpacesY
    
    #initialize the sprite group
    spotSprites = pygame.sprite.Group()
    
    #make the spaces
    for a in range(boardSpacesY):
        for b in range(boardSpacesX):
            spotName = board.pop(0)[:-1]

            x = b*spaceX + bufferX
            y = a*spaceY + bufferY
            if spotName == "Field":
                sprite = Ground(x,y)
            elif spotName == "Mountain":
                sprite = Mountain(x,y)
            elif spotName == "Water":
                sprite = Water(x,y)
            elif spotName == "Lava":
                sprite = Lava(x,y)
            elif spotName == "Magic Forest":
                sprite = MagicForest(x,y)
            elif spotName == "Gold Mine":
                sprite = GoldMine(x,y)
            elif spotName == "Forest":
                sprite = Forest(x,y)
            
            spotSprites.add(sprite)
    return spotSprites

def setupMenu():
    global menuButtons
    menuButtons = pygame.sprite.Group()
    TurnButton()
    
    
def unselect():
    if selected != None:
        selected.unselect()
        
def testAdj(a,b):
    aX = a.rect.centerx
    aY = a.rect.centery
    bX = b.rect.centerx
    bY = b.rect.centery
    
    xDiff = abs(bX-aX)
    yDiff = abs(bY-aY)
    
    offsetX = boardSizeX/boardSpacesX
    offsetY = boardSizeY/boardSpacesY
                    
    if ((xDiff==offsetX and yDiff == 0) or (yDiff==offsetY and xDiff==0)):
        return True
    else:
        return False
def testInRange(a,b,r):
    aX = a.rect.centerx
    aY = a.rect.centery
    bX = b.rect.centerx
    bY = b.rect.centery
    
    xDiff = abs(bX-aX)
    yDiff = abs(bY-aY)
    
    offsetX = boardSizeX/boardSpacesX
    offsetY = boardSizeY/boardSpacesY
    
    inRange = False
    
    for a in range(r+1):
        for b in range(r+1):
            if a+b <= r:
                x = abs(a*offsetX)
                y = abs(b*offsetY)
                if xDiff == x and yDiff == y:
                    inRange = True
    return inRange
    
def gatherResources(team):
    global resources0
    global resources1
    for mob in mobSprites:
        if mob.isWorker == True:
            if mob.team == team:
                cache = mob.occupying.resources
                for a in range(4):
                    if team==0:
                        resources0[a]+=cache[a]
                    elif team==1:
                        resources1[a]+=cache[a]

    

def aiTurn():
    global turn
    global change
    global aiCounter
    global aiMoveList
    
    
    if turn == 0:
        aiCounter = 0
    elif turn == 1:
        if aiCounter ==0:
            for mob in mobSprites:
                if mob.team==1 and mob.movement!=0:
                    aiMoveList.append(mob)
                    
        aiCounter +=1
        if len(aiMoveList) != 0 and aiCounter == 60:
            mob = aiMoveList.pop(0)
            mob.getMoves()
            unselect()
            mob.AI()
            mob.unselect()
            aiCounter = 1

        elif len(aiMoveList) ==0 and aiCounter ==60:
            aiMoveList = []
            
            aiUseCards()
            turn = 0
            change = True
            for mob in mobSprites:
                if mob.team == 0:
                    mob._turnReset()
                    
def aiUseCards():
    for card in hand1:
        if hasResources(1,card.cost):
            card.select()
            if card.availSpawns != []:
                
                randomPlace = random.randrange(0,len(card.availSpawns))
                card.action(card.availSpawns[randomPlace])
    while len(hand1) > 7:
        hand1[0].discard()
    
                    
def getDirection(a,b):
    aX = a.rect.centerx
    aY = a.rect.centery
    bX = b.rect.centerx
    bY = b.rect.centery
    
    xTot = bX - aX
    yTot = bY - aY
    
    if xTot != 0:  
        x = (xTot)*5/abs(xTot)
    else:
        x = 0
    if yTot != 0:
        y = (yTot)*5/abs(yTot)
    else:
        y = 0
    
    return x,y

def setupDeck(filename):
    filepath = os.path.join("decks",filename)
    f = open(filepath,"r")
    deck = []
    for line in f:
        if line != "end":
            deck.append(line)
        
    deck = shuffleDeck(deck)
    return deck

def shuffleDeck(deck):
    totalCards = len(deck)
    deckShuffled = []
    for a in range(totalCards):
        cardsLeft = totalCards - a
        randCardIndex = random.randrange(cardsLeft)
        randCard = deck.pop(randCardIndex)
        deckShuffled.append(randCard)
    return deckShuffled

def startingHand(team):
    for a in range(7):
        
        drawCard(team)
        
def drawCard(team):
    global hand0
    global hand1
    global deck0
    global deck1
    card = None
    if team == 0:
        cardName = deck0.pop(0)
    elif team == 1:
        cardName = deck1.pop(0)
    if cardName == "Worker\n":
        card = WorkerCard(team)
    elif cardName == "Maceman\n":
        card = MacemanCard(team)
    elif cardName == "Warrior\n":
        card = WarriorCard(team)
    elif cardName == "Brute\n":
        card = BruteCard(team)
    elif cardName == "Shock\n":
        card = ShockSpell(team)
    if card != None:
        if team == 0:
            cardSpritesSelf.add(card)          
def oppCardsSprites():
    lenNow = len(cardSpritesOpp)
    diff = len(hand1) -lenNow
    if diff != 0:
        cardSpritesOpp.clear(screen,backgroundSurface)
        cardSpritesOpp.empty()
        for a in range(len(hand1)):
            OppCard(a)
            
def startingMobs():
    global mobSprites
    squareSizeX = boardSizeX/boardSpacesX
    squareSizeY = boardSizeY/boardSpacesY
    starting0 = (bufferX + (squareSizeX*(boardSpacesX/2))+(squareSizeX/2), bufferY+(squareSizeY*boardSpacesY)-(squareSizeY/2))
    starting1 = (bufferX + (squareSizeX*(boardSpacesX/2))+(squareSizeX/2), bufferY+(squareSizeY/2))
    spawner0 = Town(starting0,0)
    spawner1 = Town(starting1,1)
    
    for spot in spotSprites:
        if spot.rect.center == starting0:
            spot.occupying = spawner0
            spawner0.occupying = spot
        elif spot.rect.center == starting1:
            spot.occupying = spawner1
            spawner1.occupying = spot
    mobSprites = pygame.sprite.Group((spawner0,spawner1))

def hasResources(team,cost):
    success = True
    if team ==0:
        for a in range(5):
            if resources0[a] < cost[a]:
                success = False
                break
    elif team ==1:
        for a in range(5):
            if resources1[a] < cost[a]:
                success = False
                break
    return success

def takeResources(team,cost):
    global resources0
    global resources1
    if team ==0:
        for a in range(5):
            resources0[a] -= cost[a]
    if team ==1:
        for a in range(5):
            resources1[a] -= cost[a]
    resourceSprites.clear(screen,backgroundSurface)
    resourceSprites.update()
def startResourceSprites():
    Food0()
    Food1()
    Wood0()
    Wood1()
    Stone0()
    Stone1()
    Gold0()
    Gold1()
    Magic0()
    Magic1()
def victoryCheck():
    global victoryCheckNow
    if victoryCheckNow:
        win0 = 1
        win1 = 1
        for mob in mobSprites:
            if mob.team == 1:
                win0 = 0
            elif mob.team == 0:
                win1 = 0
        if win1 ==1 and win0 ==0:
            Winner(1)
        elif win1 ==0 and win0==1:
            Winner(0)
        elif win1 ==0 and win0 ==0:
            victoryCheckNow = False
        else:
            Winner(2)
            
def getMaps():
    '''gets all the .map files out of the 'maps' folder'''
    
    #grab everything in there
    fullList = os.listdir('maps')
    #filter out everyting without the suffix .map
    mapList = []
    for a in fullList:
        if a[-4:] == '.map':
            mapList.append(a)
    #send back a list with just the .map files
    return mapList
        
    
def getDecks():
    '''gets all the .deck files out of the 'maps' folder'''
    
    #grab everything in there
    fullList = os.listdir('decks')
    #filter out everyting without the suffix .deck
    deckList = []
    for a in fullList:
        if a[-5:] == '.deck':
            deckList.append(a)
    #send back the list of just the .deck files
    return deckList

def renderMapsAndDecks(maps,decks):
    for a in range(len(maps)):
        MapList(maps[a],a)
    for b in range(len(decks)):
        DeckList(decks[b],b)
            
def mainMenuLoop(clock):
    #initialize the globals used
    global menuNow
    global backgroundSurface
    global screen
    
    #Create the sprite group for the buttons
    mainMenuButtons = pygame.sprite.Group()
    
    #set up the buttons on the menu
    NewGameButton(mainMenuButtons)
    DeckEditorButton(mainMenuButtons)
    MapEditorButton(mainMenuButtons)
    
    # when menuNow is set to false, the mainGameLoop will begin 
    menuNow = True
    
    # The main loop for the Menu
    while menuNow:
        clock.tick(60)
        for event in pygame.event.get(): 
            if event.type == QUIT: 
                sys.exit(0) 
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                pos= pygame.mouse.get_pos()
                for button in mainMenuButtons:
                    hitButton = button.rect.collidepoint(pos)
                    if hitButton ==1:
                        button.function()
        mainMenuButtons.draw(screen)
        pygame.display.flip()
    screen.blit(backgroundSurface,(0,0))
    startGameLoop(clock)
    
def startGameLoop(clock):
    global startNow
    global goBack
    global mapHighlights
    global deckHighlights
    global mapListSprites
    global deckListSprites
    global menuButtonList
    startNow = False
    goBack = False
    maps = getMaps()
    decks = getDecks()
    mapListSprites = pygame.sprite.Group()
    deckListSprites = pygame.sprite.Group()
    menuButtonList = pygame.sprite.Group()
    mapHighlights = pygame.sprite.Group()
    deckHighlights = pygame.sprite.Group()
    StartGameButton(menuButtonList)
    ExitMenuButton(menuButtonList)
    myMap = "field.map"
    myDeck = "default.deck"
    renderMapsAndDecks(maps,decks)
    
    # Render the 'Maps' and 'Decks' Wording
    StaticText("Choose a map",(100,55))
    StaticText("Choose your deck",(700,55))
    
    while (not startNow) and (not goBack):
        clock.tick(60)
        for event in pygame.event.get(): 
            if event.type == QUIT: 
                sys.exit(0) 
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                pos= pygame.mouse.get_pos()
                for sprite in mapListSprites:
                    if sprite.rect.collidepoint(pos):
                        myMap = sprite.function()
                for sprite in deckListSprites:
                    if sprite.rect.collidepoint(pos):
                        myDeck = sprite.function()
                for sprite in menuButtonList:
                    if sprite.rect.collidepoint(pos):
                        sprite.function()
        mapListSprites.draw(screen)
        deckListSprites.draw(screen)
        menuButtonList.draw(screen) 
        deckHighlights.draw(screen)
        mapHighlights.draw(screen)      
        pygame.display.flip()
    screen.blit(backgroundSurface,(0,0))
    if startNow:
        mainGameLoop(clock,myDeck,myMap)
    elif goBack:
        mainMenuLoop(clock)
def mainGameLoop(clock,myDeck,myMap):
    #Load the Constants
    global selected
    global screen
    global spotSprites
    global mobSprites
    global menuButtons
    global damageSprites
    global cardSpritesSelf
    global cardSpritesOpp
    global statSprites
    global smallCardSprites
    global deck0
    global deck1
    global hand0
    global hand1
    global discard0
    global discard1
    global victoryCheckNow
    global backgroundSurface
    backgroundFileName = os.path.join("data","background.png") 
    backgroundSurface = pygame.image.load(backgroundFileName) 
    screen.blit(backgroundSurface,(0,0))
    pygame.display.flip()
    
    hand0 = []
    hand1 = []
    discard0 = []
    discard1 = []
    #Initialize the playing area and sprite Groups
    spotSprites = boardSetup(myMap)
    damageSprites = pygame.sprite.Group()
    cardSpritesSelf = pygame.sprite.Group()
    cardSpritesOpp = pygame.sprite.Group()
    statSprites = pygame.sprite.Group()
    smallCardSprites = pygame.sprite.Group()
    
    #initialize the starting spawners
    startingMobs()
    startResourceSprites()
    
    victoryCheckNow = False
    
    deck0 = setupDeck(myDeck)
    deck1 = setupDeck("default.deck")
    
    setupMenu()
    startingHand(0)
    startingHand(1)
    
    while 1:
        clock.tick(60)
        for event in pygame.event.get(): 
            if event.type == QUIT: 
                sys.exit(0) 
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                pos= pygame.mouse.get_pos()
                
                mobCollide = 0
                spotCollide = 0
                
                for sprite in mobSprites:
                    
                    hitMob = sprite.rect.collidepoint(pos)
                    unselect()
                    if hitMob == 1:
                        mobCollide = 1
                                 
                        sprite.select()
                        
                        
                        break
                if mobCollide == 0 :
                    for sprite in spotSprites:
                                                
                        hitSprite = sprite.rect.collidepoint(pos)
                        
                        if hitSprite == 1:
                            
                            sprite.select()
                            
                            spotCollide = 1
                            
                            break
                    if spotCollide ==0:
                        menuCollide = 0
                        for button in menuButtons:
                            hit = button.rect.collidepoint(pos)
                            if hit == 1:
                                button.function()
                        if menuCollide == 0:
                            cardCollide =0
                            for card in cardSpritesSelf:
                                hit = card.rect.collidepoint(pos)
                                if hit == 1:
                                    cardCollide =1
                                    card.select()
                            if cardCollide ==0:
                                for card in smallCardSprites:
                                    hit = card.rect.collidepoint(pos)
                                    if hit ==1:
                                        card.select()
            
            elif event.type == MOUSEBUTTONDOWN and event.button == 3:
                rightClick = None
                pos= pygame.mouse.get_pos()
                for spot in spotSprites:
                    hitSpot = spot.rect.collidepoint(pos)
                    if hitSpot:
                        rightClick = spot
                        
                        break
                if mobSprites.has(selected) and turn ==0:
                    
                    selected.moveAction(rightClick)
                    
                if cardSpritesSelf.has(selected) and turn ==0:
                    selected.action(rightClick)
        aiTurn()
        oppCardsSprites()
        
        mobSprites.update()
        cardSpritesOpp.update()
        damageSprites.update()
        cardSpritesSelf.update()
        menuButtons.update()
        messageSprites.update()
        
        smallCardSprites.draw(screen)
        spotSprites.draw(screen)
        cardSpritesOpp.draw(screen)
        mobSprites.draw(screen)
        damageSprites.draw(screen)
        cardSpritesSelf.draw(screen)
        resourceSprites.draw(screen)
        menuButtons.draw(screen)
        statSprites.draw(screen)
        messageSprites.draw(screen)
        
        victoryCheck()
        pygame.display.flip()
def main():
    
    global screen
    selected = None
    rightClick = None
    clock = pygame.time.Clock()
    screen = screenSetup()
    mainMenuLoop(clock)
    
    
        
class BoardSpots(pygame.sprite.Sprite):
    global boardX
    global boardY
    
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)       
        self.moveSelected = False
        self.occupying = None
        self.swim = False
        self.lava = False
    def select(self):
        global selected
        unselect()
        selected = self
        self.showMenu()
        SpotHighlight(self.rect.center)
    def unselect(self):
        global selected
        selected = None
        self.image = load_image(self.imageLoad, None)
        statSprites.clear(screen,backgroundSurface)
        statSprites.empty()
    def showMenu(self):
        Name(self.name)
        x,y = (700,45)
        xAdd = 10
        yAdd = 0
        if self.resources[0] != 0:
            costSprite = Cost(self.resources[0],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            FoodSprite((x2,y2))
            y += 25
        if self.resources[1] != 0:
            costSprite = Cost(self.resources[1],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            WoodSprite((x2,y2))
            y += 25
        if self.resources[2] != 0:
            costSprite = Cost(self.resources[2],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            StoneSprite((x2,y2))
            y += 25
        if self.resources[3] != 0:
            costSprite = Cost(self.resources[3],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            GoldSprite((x2,y2))
            y += 25
        if self.resources[4] != 0:
            costSprite = Cost(self.resources[4],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            MagicSprite((x2,y2))
            y += 25
class Ground(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Field"
        self.imageLoad = "ground.png"
        self.imageSelLoad = "groundS.png"
        self.imageAttackLoad = "groundA.png"
        self.imageMoveLoad = "groundM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [1,0,0,0,0]

class Forest(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Forest"
        self.imageLoad = "forrest.png"
        self.imageSelLoad = "forrestS.png"
        self.imageAttackLoad = "forrestA.png"
        self.imageMoveLoad = "forrestM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [0,1,0,0,0]
class MagicForest(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Magic Forest"
        self.imageLoad = "magicForrest.png"
        self.imageSelLoad = "magicForrestS.png"
        self.imageAttackLoad = "magicForrestA.png"
        self.imageMoveLoad = "magicForrestM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [0,0,0,0,1]
class GoldMine(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Gold Mine"
        self.imageLoad = "goldMine.png"
        self.imageSelLoad = "goldMineS.png"
        self.imageAttackLoad = "goldMineA.png"
        self.imageMoveLoad = "goldMineM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [0,0,0,1,0]
class Mountain(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Mountain"
        self.imageLoad = "mountain.png"
        self.imageSelLoad = "mountainS.png"
        self.imageAttackLoad = "mountainA.png"
        self.imageMoveLoad = "mountainM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [0,0,1,0,0]

class Water (BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Water"
        self.imageLoad = "water.png"
        self.imageSelLoad = "waterS.png"
        self.imageAttackLoad = "waterA.png"
        self.imageMoveLoad = "waterM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.swim = True
        self.resources = [0,0,0,0,0]
        
class Lava(BoardSpots):
    def __init__(self,x,y):
        BoardSpots.__init__(self)
        self.name = "Lava"
        self.lava = True
        self.imageLoad = "lava.png"
        self.imageSelLoad = "lavaS.png"
        self.imageAttackLoad = "lavaA.png"
        self.imageMoveLoad = "lavaM.png"
        self.image = load_image(self.imageLoad, None)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.resources = [0,0,0,0,0]
    
class Mob(pygame.sprite.Sprite):
    
    def __init__(self,mid,team):
        pygame.sprite.Sprite.__init__(self)
        
        self.team = team
        self.isSpawn = False
        self.isWorker = False
        self.canSwim = False
        self.canLava = False
        self.unit = False
        self.building = False
        if self.team == 0:
            self.imageLoad = "workerBlue.png"
            self.imageSelLoad = "workerBlueS.png"
        elif self.team == 1:
            self.imageLoad = "workerRed.png"
            self.imageSelLoad = "workerRedS.png"
        self.cardImage = "card.jpg"
        self.image = load_image(self.imageLoad, -1)
        self.rect = self.image.get_rect()
        self.rect.center = mid
        self.selected = 0
        self.occupying = None
        self.availMoves = []
        self.moveAmounts = []
        self.availAttacks = []
        self.moveSpeed = 1
        self.destination = None
        self.moveX = 0
        self.moveY = 0
        self.attacking = None
        self.offset = 0
        self.multiplyer = 1
        self.spinCounter = 0    
        
        self.totalMovement =5
        self.movement = 0
        self.health = 5
        self.attack = 1
        self.range = 1
        
        self.flav = '"This is a default mob"'
    def update(self):
        if self.health <= 0:
            
            self._death()
        if self.destination != None:
            
            self._move()
        elif self.attacking != None:
            
            self._attack(self.attacking)
    def _turnReset(self):
        self.movement = self.totalMovement
    def attackMob(self,target):
        adj = testAdj(self,target)
        if adj:
            self.health -= target.attack
        target.health -= self.attack
        self.movement = 0
        self.unselect()
    def canTravelHere(self,spot):
        if spot.swim and not self.canSwim:
            return False
        elif spot.lava and not self.canLava:
            return False
        else:
            return True
        
    def getMoves(self):
        numMoves = 1
        moves = [self.occupying]
        
        switcher = False
        for a in range(self.movement):
            if not switcher:
                moves2 = []
                for b in moves:
                    
                    for spot in spotSprites:
                                          
                        if spot not in self.availMoves:
                            adj = testAdj(b,spot)
                            inRange = testInRange(b,spot,self.range) 
                            if spot.occupying == None:
                                if self.canTravelHere(spot)and adj:
                                    SpotMove(spot.rect.center)
                                    spot.moveSelected = True
                                    moves2.append(spot)
                                    self.availMoves.append(spot)
                                    self.moveAmounts.append((spot,numMoves))
                            elif spot.occupying.team != self.team and inRange:
                                if spot not in self.availAttacks:
                                    self.availAttacks.append(spot)
                                    SpotAttack(spot.rect.center)
                        
                        
                switcher = True
                
            elif switcher:
                moves = []
                for b in moves2:
                    
                    for spot in spotSprites:
                                            
                        if spot not in self.availMoves:
                            adj = testAdj(b,spot)
                            inRange = testInRange(b,spot,self.range)
                            if spot.occupying == None:
                                if self.canTravelHere(spot)and adj:
                                    SpotMove(spot.rect.center)
                                    spot.moveSelected = True
                                    moves.append(spot)
                                    self.availMoves.append(spot)
                                    self.moveAmounts.append((spot,numMoves))
                            elif spot.occupying.team != self.team and inRange:
                                if spot not in self.availAttacks:
                                    self.availAttacks.append(spot)
                                    SpotAttack(spot.rect.center)
                switcher = False
            numMoves += 1
    def _death(self):
        global selected
        global victoryCheckNow
        center = self.rect.center
        self.spinCounter += 10
        self.image = pygame.transform.rotate(self.deathImage, self.spinCounter)
        self.rect = self.image.get_rect(center=center)
        if self.spinCounter == 360:
            if selected == self:
                selected = None
            self.occupying.occupying=None
            
            victoryCheckNow = True
            self.kill()
            self.spinCounter = 0
            
            del self
    
    def _attack(self,target):
        
        if self.offset == 0:
            self.adj = testAdj(self,target)
        x,y = getDirection(self,target)
        x *= self.multiplyer
        y *= self.multiplyer
        
        
        self.rect = self.rect.move(x,y)
        if self.adj:
            target.rect = target.rect.move(-x,-y)
        self.offset += 1
        if self.offset == 6:
            damageOtherTxt = "-" + str(self.attack)
            otherLoc = target.rect.center
            CombatText(damageOtherTxt,otherLoc)
            if self.adj:
                damageSelfTxt = "-" + str(target.attack)
                selfLoc = self.rect.center
                CombatText(damageSelfTxt,selfLoc)
            self.multiplyer = -self.multiplyer
        elif self.offset == 12:
            self.attackMob(self.attacking)
            self.attacking = None
            self.multiplyer = -self.multiplyer
            self.offset = 0
    def select(self):
        global selected
        
        unselect()
        selected = self
        MobHighlight(self.rect.center)
        self.showMenu()
        if self.team == turn:
            self.getMoves()
    def unselect(self):
        global selected
        self.image= load_image(self.imageLoad, -1)
        selected = None
        
        statSprites.clear(screen,backgroundSurface)
        statSprites.empty()
        
        for spot in self.availMoves:
            
            spot.image = load_image(spot.imageLoad,None)
                
        for spot in self.availAttacks:
            spot.image = load_image(spot.imageLoad,None)
        self.availMoves = []
        self.availAttacks = []
        self.moveAmounts = []
    def moveAction(self,spaceClicked):
        if spaceClicked in self.availAttacks and self.movement != 0:
            self.attacking = spaceClicked.occupying
            
            
            if not testInRange(self,spaceClicked,self.range):
                closest = self._getClosestInRange(spaceClicked)
            
                self.moveAction(closest)
                    
        else:
            for a in self.moveAmounts:
                if a[0] == spaceClicked:
                    self.occupying.occupying = None
                    aX = self.rect.centerx
                    aY = self.rect.centery
                    bX = spaceClicked.rect.centerx
                    bY = spaceClicked.rect.centery
                    rawX = bX - aX
                    rawY = bY - aY
                    moveFactor = 10
                    self.moveX = rawX/moveFactor
                    self.moveY = rawY/moveFactor
                    self.destination = spaceClicked
                    self.unselect()
                    if self.movement >= a[1]:
                        self.movement -= a[1]
                    else:
                        self.movement = 0
                    break
                
    def _getClosestInRange(self,space):
        smallestSoFar = 99
        
        for a in self.moveAmounts:
            
            if testInRange(a[0],space,self.range) and (a[1] < smallestSoFar):
                closest = a[0]
                smallestSoFar = a[1]
        return closest
    def _move(self):
        
        pos = self.rect.center
        if pos == self.destination.rect.center:
            self.occupying = self.destination
            self.destination.occupying = self
            self.destination = None
            self.moveX = 0
            self.moveY = 0
            if self.movement != 0 and self.team == 0:
                self.select()
            
        else:
            newpos = self.rect.move(self.moveX,self.moveY)
            self.rect = newpos
            
            
            
    def showMenu(self):
        Name(self.name)
        IconSprite(self.imageLoad)
        Info(self.info)
        x,y = 700,175
        if self.attack < 9:
            for a in range(self.attack):
                AttackSprite((x,y))
                x += 20
        else:
            sprite = Cost(self.attacking,(x,y))
            x = sprite.rect.topright[0] + 5
            AttackSprite((x,y+4))
        y += 25
        x = 700
        if self.health < 9:
            for a in range(self.health):
                HealthSprite((x,y))
                x += 20
        else:
            sprite = Cost(self.health,(x,y))
            x = sprite.rect.topright[0] + 5
            HealthSprite((x,y+4))
        y += 25
        x = 700
        if self.movement < 9:
            for a in range(self.movement):
                MovementSprite((x,y))
                x +=20
        else:
            sprite = Cost(self.movement,(x,y))
            x = sprite.rect.topright[0] + 5
            MovementSprite((x,y+4))
        y += 25
        x = 700
        
        if self.range < 9:
            for a in range(self.range):
                RangeSprite((x,y))
                x+=20
        else:
            sprite = Cost(self.range,(x,y))
            x = sprite.rect.topright[0] + 5
            RangeSprite((x,y+4))
    def AI(self):
        mobRange = len(self.availAttacks)
        spaceRange = len(self.availMoves)
        
        target = None
        if mobRange > 0:
            for a in range(mobRange):
                randIndex = random.randrange(0,mobRange)
                randMob = self.availAttacks[randIndex].occupying
                selfTotalStats = self.attack + self.health
                oppTotalStats = randMob.attack + randMob.health
                diff = selfTotalStats - oppTotalStats
                if diff > 0:
                    target = randMob.occupying
                    
                else:
                    chance = float(selfTotalStats)/float(oppTotalStats)
                    randTest = random.random()
                    if randTest <= chance:
                        target = randMob.occupying
                if target != None:
                    
                    break
                            
        elif spaceRange >0:
            for a in range(spaceRange):
                randIndex = random.randrange(0,spaceRange)
                randSpace = self.availMoves[randIndex]
                spaceAmount = boardSizeY/boardSpacesY
                a = 2*spaceAmount*self.totalMovement
                b = (spaceAmount*self.totalMovement)+(randSpace.rect.centery-self.rect.centery)
                randTest = random.random()
                probability = float(b)/float(a)
                if probability >= randTest:
                    target = randSpace
                    
                    break
        if target != None:
            
            self.moveAction(target)
        
class Warrior(Mob):
    def __init__(self,mid,team):
        Mob.__init__(self,mid,team)
        self.totalMovement = 3
        self.name = "Warrior"
        self.info = "A cheap yet relatively weak fighting unit."
        self.health = 3
        self.attack = 2
        self.range = 2
        self.unit = True
        if self.team == 0:
            self.imageLoad = "warriorBlue.png"
            self.imageSelLoad = "warriorBlueS.png"
        elif self.team ==1:
            self.imageLoad = "warriorRed.png"
            self.imageSelLoad = "warriorRedS.png"
        self.image = load_image(self.imageLoad,-1)
        self.deathImage = self.image
        
class Maceman(Mob):
    def __init__(self,mid,team):
        Mob.__init__(self,mid,team)
        self.name = "Maceman"
        self.info = "A standard military unit."
        self.totalMovement = 1
        self.health = 4
        self.attack = 2
        self.unit = True
        if self.team == 0:
            self.imageLoad = "macemanBlue.png"
            self.imageSelLoad = "macemanBlueS.png"
        elif self.team ==1:
            self.imageLoad = "macemanRed.png"
            self.imageSelLoad = "macemanRedS.png"
        self.image = load_image(self.imageLoad,-1)
        self.deathImage = self.image
        
class Brute(Mob):
    def __init__(self,mid,team):
        Mob.__init__(self,mid,team)
        self.name = "Brute"
        self.info = "A heavy melee unit."
        self.totalMovement = 1
        self.health = 5
        self.attack = 5
        self.unit = True
        if self.team == 0:
            self.imageLoad = "bruteBlue.png"
            self.imageSelLoad = "bruteBlueS.png"
        elif self.team ==1:
            self.imageLoad = "bruteRed.png"
            self.imageSelLoad = "bruteRedS.png"
        self.image = load_image(self.imageLoad,-1)
        self.deathImage = self.image
        
class Town(Mob):
    def __init__(self,mid,team):
        Mob.__init__(self,mid,team)
        self.totalMovement = 0
        self.name = "Town"
        self.info = "New units can be spawned anywhere adjacent to \na town"
        self.health = 10
        self.attack = 0
        self.range = 0
        self.isSpawn = True
        self.building = True
        if self.team == 0:
            self.imageLoad = "townBlue.png"
            self.imageSelLoad = "townBlueS.png"
        elif self.team ==1:
            self.imageLoad = "townRed.png"
            self.imageSelLoad = "townRedS.png"
        self.image = load_image(self.imageLoad,-1)
        self.deathImage = self.image
        
class Worker(Mob):
    def __init__(self,mid,team):
        Mob.__init__(self,mid,team)
        self.name = "Worker"
        self.info = "A very weak unit which gathers resources at the \nbeginning of your turn from the space which it \nis standing on."
        self.totalMovement = 1
        self.isWorker = True
        self.health = 2
        self.attack = 1
        self.unit = True
        if self.team ==0:
            self.imageLoad = "workerBlue.png"
            self.imageSelLoad = "workerBlueS.png"
        elif self.team ==1:
            self.imageLoad = "workerRed.png"
            self.imageSelLoad = "workerRedS.png"
        self.image = load_image(self.imageLoad,-1)
        self.cardImage = "worker.png"
        self.deathImage = self.image
        
class Stats(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.font = pygame.font.Font(None,24)
        self.color = (0,0,0)
        statSprites.add(self)
class SpotHighlight(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("spotSelected.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
class SpotAttack(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("spotAttack.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
class SpotMove(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("spotMove.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
class MobHighlight(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("unitSelected.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
class LittleCardHighlight(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("unitSmallSelect.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
class Name(Stats):
    def __init__(self,name):
        Stats.__init__(self)
        self.text = name
        self.font = pygame.font.Font(None,40)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.image.get_rect()
        self.rect.center = (785,30)
class IconSprite(Stats):
    def __init__(self,image):
        Stats.__init__(self)
        self.image = load_image(image,-1)
        self.rect = self.image.get_rect()
        self.rect.midtop = (825,50)
class Cost(Stats):
    def __init__(self,amount,loc):
        Stats.__init__(self)
        self.text = str(amount)
        self.font = pygame.font.Font(None,36)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class Info(Stats):
    def __init__(self,text,line=0):
        Stats.__init__(self)
        self.color = (0,0,0)
        self.font = pygame.font.Font(None,24)
        textList = text.split("\n")
        self.surface = self.font.render(textList[0],1,self.color)
        if len(textList) > 1:
            textList.pop(0)
            counter = 1
            for a in textList:
                Info(a,counter) 
                counter += 1
        self.image = self.surface
        self.rect = self.image.get_rect()
        pos = (885,30+(20*line))
        self.rect.topleft = pos
class FoodSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("food.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class WoodSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("wood.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class StoneSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("stone.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class GoldSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("gold.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class MagicSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("magic.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class AttackSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("attackSprite.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class HealthSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("healthSprite.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class MovementSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("movementSprite.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
class RangeSprite(Stats):
    def __init__(self,loc):
        Stats.__init__(self)
        self.image = load_image("rangeSprite.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = loc
        
class Winner(pygame.sprite.Sprite):
    def __init__(self,winner):
        pygame.sprite.Sprite.__init__(self)
        if winner == 0:
            text = "YOU'RE WINNER!"
        elif winner == 1:
            text = "YOU'RE LOSER!"
        elif winner == 2:
            text = "YOU'RE TIE'RE(?)"
        color = (250,250,250)
        self.font = pygame.font.Font(None,200)
        self.surface =self.font.render(text,1,color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.center = (1280/2,720/2)
        messageSprites.add(self)
        
class Resources(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.font = pygame.font.Font(None,24)
        resourceSprites.add(self)
class Food1(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources1[0])
        self.color = (0,0,0)
        self.loc =(bufferX+30,15)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources1[0])
        self.image = self.font.render(self.text,1,self.color)
class Food0(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources0[0])
        self.color = (0,0,0)
        self.loc =(bufferX+30,690)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources0[0])
        self.image = self.font.render(self.text,1,self.color)
        
class Wood1(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources1[1])
        self.color = (0,0,0)
        self.loc =(bufferX+95,15)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources1[1])
        self.image = self.font.render(self.text,1,self.color)
class Wood0(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources0[1])
        self.color = (0,0,0)
        self.loc =(bufferX+95,690)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources0[1])
        self.image = self.font.render(self.text,1,self.color)
class Stone1(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources1[2])
        self.color = (0,0,0)
        self.loc =(bufferX+160,15)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources1[2])
        self.image = self.font.render(self.text,1,self.color)
class Stone0(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources0[2])
        self.color = (0,0,0)
        self.loc =(bufferX+160,690)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources0[2])
        self.image = self.font.render(self.text,1,self.color)
class Gold1(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources1[3])
        self.color = (0,0,0)
        self.loc =(bufferX+225,15)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources1[3])
        self.image = self.font.render(self.text,1,self.color)
class Gold0(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources0[3])
        self.color = (0,0,0)
        self.loc =(bufferX+225,690)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources0[3])
        self.image = self.font.render(self.text,1,self.color)
        
class Magic1(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources1[4])
        self.color = (0,0,0)
        self.loc =(bufferX+290,15)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources1[4])
        self.image = self.font.render(self.text,1,self.color)
      
class Magic0(Resources):
    def __init__(self):
        Resources.__init__(self)
        self.text = str(resources0[4])
        self.color = (0,0,0)
        self.loc =(bufferX+290,690)
        self.surface = self.font.render(self.text,1,self.color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.topleft = self.loc
    def update(self):
        self.text = str(resources0[4])
        self.image = self.font.render(self.text,1,self.color)

class BigCard(pygame.sprite.Sprite):
    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image(image,-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (750,70)
        bigCardSprites.add(self)
        
class MenuButton(pygame.sprite.Sprite):
    def __init__(self):
        global menuButtons
        pygame.sprite.Sprite.__init__(self)
        menuButtons.add(self)
        self.turns = -1
        self.activated = 1
    
            
class TurnButton(MenuButton):
    def __init__(self):
        MenuButton.__init__(self)
        self.defaultImage = "turnButton.png"
        self.disabledImage = "turnButtonG.png"
        self.image = load_image(self.defaultImage,-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (688,677)
        self.turns = 0
    def function(self):
        global turn
        if turn ==0:
            if len(hand0)<8:
                global change
                turn = 1
                change = True
                for mob in mobSprites:
                    if mob.team == 1:
                        mob._turnReset()
            else:
                Error("You must discard first.")
    def update(self):
        global change
        if change == True:
            if turn == 0:
                self.image = load_image(self.defaultImage,-1)
            elif turn == 1:
                self.image = load_image(self.disabledImage,-1)
            drawCard(turn)
            gatherResources(turn)
            resourceSprites.clear(screen,backgroundSurface)
            resourceSprites.update()
            change = False
class Discard(MenuButton):
    def __init__(self,card):
        MenuButton.__init__(self)
        self.image = load_image("discard.png",None)
        self.rect = self.image.get_rect()
        self.rect.bottomleft = (card.rect.bottomleft)
        self.card = card
        self.killIt = False
    def function(self):
        unselect()
        self.card.discard()
    def update(self):
        if self.killIt:
            menuButtons.clear(screen,backgroundSurface)
            self.kill()
            
            del self
class CombatText(pygame.sprite.Sprite):
    def __init__(self,text,loc):
        pygame.sprite.Sprite.__init__(self)
        self.font = pygame.font.Font(None,24)
        self.surface = self.font.render(text,1,(255,0,0))
        self.image = self.surface
        self.rect = self.image.get_rect()
        self.rect.bottomright = loc
        self.counter = 0
        damageSprites.add(self)
    
    def update(self):
        self.rect = self.rect.move(0,2)
        self.counter += 1
        if self.counter > 20:
            self.kill()
            del self
            
class LittleCard(pygame.sprite.Sprite):
    def __init__(self,card):
        pygame.sprite.Sprite.__init__(self)
        self.name = card.name
        if card.unit:
            self.attack = card.attack
            self.health = card.health
            self.movement = card.movement
            self.range = card.range
        elif card.spell:
            self.attack = card.attack
        self.info = card.info
        self.iconImage = card.iconImage
        self.tinyImage = card.tinyImage
        self.image = load_image(self.tinyImage,-1)
        self.rect = self.image.get_rect()
        self.cost = card.cost
        self.team = card.team
        self.unit = card.unit
        self.building = card.building
        self.spell = card.spell
        self.position = -1
        smallCardSprites.add(self)
        for sprite in smallCardSprites:
            if sprite.team == self.team:
                sprite.position +=1
                if sprite.position == 10:
                    smallCardSprites.clear(screen,backgroundSurface)
                    sprite.kill()
        smallCardSprites.update()
    def update(self):
        if self.team ==0:
            self.rect.topleft = (1240,313+self.position*33)
        elif self.team ==1:
            self.rect.topleft = (5,368 + self.position*33)
    def select(self):
        Name(self.name)
        IconSprite(self.iconImage)
        Info(self.info)
        LittleCardHighlight(self.rect.center)
        x,y = (700,45)
        xAdd = 10
        yAdd = 0
        if self.cost[0] != 0:
            costSprite = Cost(self.cost[0],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            FoodSprite((x2,y2))
            y += 25
        if self.cost[1] != 0:
            costSprite = Cost(self.cost[1],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            WoodSprite((x2,y2))
            y += 25
        if self.cost[2] != 0:
            costSprite = Cost(self.cost[2],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            StoneSprite((x2,y2))
            y += 25
        if self.cost[3] != 0:
            costSprite = Cost(self.cost[3],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            GoldSprite((x2,y2))
            y += 25
        if self.cost[4] != 0:
            costSprite = Cost(self.cost[4],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            MagicSprite((x2,y2))
            y += 25
        if self.unit == True:
            y = 175
            xAdd = 10
            yAdd = 0
            for a in range(self.attack):
                AttackSprite((x,y))
                x += 20
            y += 25
            x = 700
            for a in range(self.health):
                HealthSprite((x,y))
                x += 20
            y += 25
            x = 700
            for a in range(self.movement):
                MovementSprite((x,y))
                x +=20
            y += 25
            x = 700
            for a in range(self.range):
                RangeSprite((x,y))
                x +=20
        
class Card(pygame.sprite.Sprite):
    def __init__(self,team):
        global hand0
        global hand1
        pygame.sprite.Sprite.__init__(self)
        self.selectedImage = "workerCardS.png"
        self.defaultImage = "workerCard.png"
        self.availSpawns = []
        self.team = team
        self.spell = False
        self.unit = False
        self.building = False
        self.destinationPos = None
        self.moveAmountX = None
        self.moveAmountY = None
        self.newCard = True
        self.range = 1
        
        
        if self.team == 1:
            hand1.append(self)
            self.position = hand1.index(self)
            
        elif self.team == 0:
            self.image = load_image(self.defaultImage,-1)
            self.rect = self.image.get_rect()
            hand0.append(self)
            
            self.position = hand0.index(self)
            cardSpritesSelf.add(self)
            self.rect.topleft = (1270,335)
            self.reorder()
            
    def update(self):
        if change == True and self.team ==0:
            self.reorder()
        if self.destinationPos != None:
            self._move()
            
    def discard(self):
        if self.team == 0:
            cardSpritesSelf.clear(screen,backgroundSurface)
            tempIndex = hand0.index(self)
            hand0.pop(tempIndex)
            LittleCard(self)
        if self.team == 1:
            tempIndex = hand1.index(self)
            hand1.pop(tempIndex)
            LittleCard(self)
        self.kill()
        del self
    def _move(self):
        self.rect = self.rect.move(self.moveAmountX,self.moveAmountY)
        cardSpritesSelf.clear(screen,backgroundSurface)
        if self.rect.topleft == self.destinationPos:
            self.destinationPos = None
            self.moveAmountX = None
            self.moveAmountY = None
    def action(self,rightClick):
        if hasResources(self.team,self.cost):
            if rightClick in self.availSpawns:
                takeResources(self.team,self.cost)
                if self.unit == True:
                    loc = rightClick.rect.center
                    mob = self.spawn(loc)
                    mob.occupying = rightClick
                    rightClick.occupying = mob
                    mobSprites.add(mob)
                elif self.spell == True:
                    self.spellAction(rightClick)
                unselect()
                self.reorder()
                LittleCard(self)
                if self.team ==0:
                    hand0.pop(self.position)
                    cardSpritesSelf.clear(screen,backgroundSurface)
                if self.team ==1:
                    self.position = hand1.index(self)
                    hand1.pop(self.position)
                self.kill()
                del self
        else:
            Error("You don't have enough resources.")
    def select(self):
        global selected
        self.image = load_image(self.selectedImage,-1)
        unselect()
        selected = self
        if self.team ==turn:
            self.getSpawns()
        if self.team == 0:
            self.discardSprite = Discard(self)
        self.selectedSprites()
    def selectedSprites(self):
        Name(self.name)
        IconSprite(self.iconImage)
        Info(self.info)
        x,y = (700,45)
        xAdd = 10
        yAdd = 0
        if self.cost[0] != 0:
            costSprite = Cost(self.cost[0],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            FoodSprite((x2,y2))
            y += 25
        if self.cost[1] != 0:
            costSprite = Cost(self.cost[1],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            WoodSprite((x2,y2))
            y += 25
        if self.cost[2] != 0:
            costSprite = Cost(self.cost[2],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            StoneSprite((x2,y2))
            y += 25
        if self.cost[3] != 0:
            costSprite = Cost(self.cost[3],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            GoldSprite((x2,y2))
            y += 25
        if self.cost[4] != 0:
            costSprite = Cost(self.cost[4],(x,y))
            x2,y2 = costSprite.rect.topright
            x2 += xAdd
            y2 -= yAdd
            MagicSprite((x2,y2))
            y += 25
        if self.unit == True:
            y = 175
            xAdd = 10
            yAdd = 0
            for a in range(self.attack):
                AttackSprite((x,y))
                x += 20
            y += 25
            x = 700
            for a in range(self.health):
                HealthSprite((x,y))
                x += 20
            y += 25
            x = 700
            for a in range(self.movement):
                MovementSprite((x,y))
                x +=20
            y += 25
            x = 700
            for a in range(self.range):
                RangeSprite((x,y))
                x +=20
                
                
    def getSpawns(self):
        if self.unit:
            for mob in mobSprites:
                if mob.team == self.team and mob.isSpawn == True:
                    for spot in spotSprites:
                        if testAdj(mob,spot) and spot.occupying == None:
                            self.availSpawns.append(spot)
                            SpotMove(spot.rect.center)
        elif self.spell:
            for mob in mobSprites:
                if mob.unit == True:
                    self.availSpawns.append(mob.occupying)
                    SpotMove(mob.occupying.rect.center)
                
    def unselect(self):
        global selected
        self.image = load_image(self.defaultImage, -1)
        statSprites.clear(screen,backgroundSurface)
        statSprites.empty()
        if self.team == 0:
            self.discardSprite.killIt = True
        self.availSpawns = []
        
    def reorder(self):
        if self.team ==0:
            oldPos = self.position
            self.position = hand0.index(self)
        
            if oldPos != self.position or self.newCard ==True:
                if self.position < 4:
                    posX,posY = 690+self.position*135,295
                else:
                    posX,posY = 690+(self.position-4)*135,480
                oldPosX,oldPosY = self.rect.topleft
                self.destinationPos = posX,posY
                self.moveAmountX = (posX-oldPosX)/5
                self.moveAmountY = (posY-oldPosY)/5
                self.newCard = False
    
class WorkerCard(Card):
    def __init__(self,team):
        Card.__init__(self,team)
        self.cost = [2,0,0,0,0]
        self.name = "Worker"
        self.info = "A very weak unit which gathers resources at the \nbeginning of your turn from the space which it \nis standing on."
        self.unit = True
        self.attack = 1
        self.health = 2
        self.movement = 1
        if self.team==0:
            self.iconImage = "workerBlue.png"
            self.tinyImage = "workerSmallBlue.png"
        elif self.team==1:
            self.iconImage = "workerRed.png"
            self.tinyImage = "workerSmallRed.png"
        self.defaultImage = "workerCard.png"
        self.selectedImage = "workerCardS.png"
        self.image = load_image(self.defaultImage,-1)
    def spawn(self,mid):
        mob = Worker(mid,self.team)
        return mob
    
class WarriorCard(Card):
    def __init__(self,team):
        Card.__init__(self,team)
        self.name = "Warrior"
        self.info = "A cheap yet relatively weak fighting unit."
        self.unit = True
        self.attack = 2
        self.health = 3
        self.movement = 1
        self.range = 2
        self.cost = [3,0,0,0,0]
        if self.team==0:
            self.iconImage = "warriorBlue.png"
            self.tinyImage = "warriorSmallBlue.png"
        elif self.team==1:
            self.iconImage = "warriorRed.png"
            self.tinyImage = "warriorSmallRed.png"
        self.defaultImage = "warriorCard.png"
        self.selectedImage = "warriorCardS.png"
        self.image = load_image(self.defaultImage,-1)
    def spawn(self,mid):
        mob = Warrior(mid,self.team)
        return mob
    
class MacemanCard(Card):
    def __init__(self,team):
        Card.__init__(self,team)
        self.name = "Maceman"
        self.info = "A standard military unit."
        self.unit = True
        self.attack = 2
        self.health = 4
        self.movement = 1
        self.cost = [0,1,0,2,0]
        if self.team==0:
            self.iconImage = "macemanBlue.png"
            self.tinyImage = "macemanSmallBlue.png"
        elif self.team==1:
            self.iconImage = "macemanRed.png"
            self.tinyImage = "macemanSmallRed.png"
        self.defaultImage = "macemanCard.png"
        self.selectedImage = "macemanCardS.png"
        self.image = load_image(self.defaultImage,-1)
    def spawn(self,mid):
        mob = Maceman(mid,self.team)
        return mob
    
class BruteCard(Card):
    def __init__(self,team):
        Card.__init__(self,team)
        self.name = "Brute"
        self.info = "A heavy melee unit."
        self.unit = True
        self.attack = 5
        self.health = 5
        self.movement = 1
        self.cost = [2,2,2,2,0]
        if self.team==0:
            self.iconImage = "bruteBlue.png"
            self.tinyImage = "bruteSmallBlue.png"
        elif self.team==1:
            self.iconImage = "bruteRed.png"
            self.tinyImage = "bruteSmallRed.png"
        self.defaultImage = "bruteCard.png"
        self.selectedImage = "bruteCardS.png"
        self.image = load_image(self.defaultImage,-1)
    def spawn(self,mid):
        mob = Brute(mid,self.team)
        return mob
    
#
#
#    Spell Cards
#

class ShockSpell(Card):
    def __init__(self,team):
        Card.__init__(self,team)
        self.name = "Shock"
        self.info = "A basic damage spell. \nCannot be used against buildings."
        self.iconImage = "shockSpell.png"
        self.tinyImage = "shockSpellSmall.png"
        self.defaultImage = "shockSpellCard.png"
        self.selectedImage = "shockSpellCardS.png"
        self.image = load_image(self.defaultImage,-1)
        
        self.spell = True
        self.attack = 3
        self.cost = [0,0,0,0,2]
    def spellAction(self,target):
        target.occupying.health -= self.attack
        CombatText("-"+str(self.attack),target.rect.center)

class Error(pygame.sprite.Sprite):
    def __init__(self,text):
        pygame.sprite.Sprite.__init__(self)
        color = (250,0,0)
        self.font = pygame.font.Font(None,30)
        self.surface =self.font.render(text,1,color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.center = (1280/2,250 + len(messageSprites)*30)
        messageSprites.add(self)
        self.activated = True
        self.counter = 0
    def update(self):
        if self.activated == True:
            self.counter +=1
            if self.counter >= 80:
                messageSprites.clear(screen,backgroundSurface)
                self.kill()
                del self
class OppCard(pygame.sprite.Sprite):
    def __init__(self,index):
        pygame.sprite.Sprite.__init__(self)
        cardSpritesOpp.add(self)
        self.index = index
        
        self.image = load_image("cardSmall.png",-1)
        self.rect = self.image.get_rect()
        YOffset = index * 41
        pos = (7,20+YOffset)
        
        self.rect.topleft = pos
    def update(self):
        
        if self.index > (len(hand1)-1):
            self.kill()
            del self                
#Main Menu Classes

class MainMenuButton(pygame.sprite.Sprite):
    def __init__(self,group):
        pygame.sprite.Sprite.__init__(self)
        group.add(self)
class StartGameButton(MainMenuButton):
    def __init__(self,group):
        MainMenuButton.__init__(self,group)
        self.image = load_image("startGameButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = (screenSizeX/2+75,660)
    def function(self):
        global startNow
        startNow = True
        
class ExitMenuButton(MainMenuButton):
    def __init__(self,group):
        MainMenuButton.__init__(self,group)
        self.image = load_image("exitButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = (screenSizeX/2-75,660)
    def function(self):
        global goBack
        goBack = True
class NewGameButton(MainMenuButton):
    def __init__(self,group):
        MainMenuButton.__init__(self,group)
        self.image = load_image("newGameMenuButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = (screenSizeX/2,(screenSizeY/2)-200)
    def function(self):
        global menuNow
        menuNow = False
class DeckEditorButton(MainMenuButton):
    def __init__(self,group):
        MainMenuButton.__init__(self,group)
        self.image = load_image("deckEditorMenuButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = (screenSizeX/2,(screenSizeY/2))
    def function(self):
        global screen
        theScreen = screen
        DeckEditor.run(theScreen)
class MapEditorButton(MainMenuButton):
    def __init__(self,group):
        MainMenuButton.__init__(self,group)
        self.image = load_image("mapEditorMenuButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = (screenSizeX/2,(screenSizeY/2)+200)
    def function(self):
        global screen
        theScreen = screen
        MapEditor.run(theScreen)

#start menu selection classes
class MapList(pygame.sprite.Sprite):
    def __init__(self,text,pos):
        global mapListSprites
        pygame.sprite.Sprite.__init__(self)
        self.text = text
        self.font = pygame.font.Font(None,24)
        self.surface = self.font.render(text,1,(0,0,0))
        self.image = self.surface
        self.rect = self.image.get_rect()
        x = 100
        y = 100 + pos*30
        self.rect.topleft = (x,y)
        mapListSprites.add(self)
    def function(self):
        global mapHighlights
        mapHighlights.clear(screen,backgroundSurface)
        mapHighlights.empty()
        highlight = ListHighlight(self.rect.midleft)
        mapHighlights.add(highlight)
        return self.text
class DeckList(pygame.sprite.Sprite):
    def __init__(self,text,pos):
        global deckListSprites
        pygame.sprite.Sprite.__init__(self)
        self.text = text
        self.font = pygame.font.Font(None,24)
        self.surface = self.font.render(text,1,(0,0,0))
        self.image = self.surface
        self.rect = self.image.get_rect()
        x = 700
        y = 100 + pos*30
        self.rect.topleft = (x,y)
        deckListSprites.add(self)
    def function(self):
        global deckHighlights
        deckHighlights.clear(screen,backgroundSurface)
        deckHighlights.empty()
        highlight = ListHighlight(self.rect.midleft)
        deckHighlights.add(highlight)
        return self.text
        
class ListHighlight(pygame.sprite.Sprite):
    def __init__(self,pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image("startMenuSelect.png",-1)
        self.rect = self.image.get_rect()
        x = pos[0]-10
        y = pos[1]
        self.rect.midleft = (x,y)
        
class StaticText():
    def __init__(self,text,loc,size=36):
        self.font = pygame.font.Font(None,size)
        surface = self.font.render(text,1,(0,0,0))
        screen.blit(surface,loc)

if __name__=="__main__":
    main()